package com.tiancai.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tiancai.context.BaseContext;
import com.tiancai.pojo.po.WorkRent;
import com.tiancai.result.Result;
import com.tiancai.service.IWorkRentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tiancai
 * @since 2025-04-13
 */
@RestController
@RequestMapping("/work-rent")
@Tag(name = "作品租赁管理")
@Slf4j
@CrossOrigin
public class WorkRentController {

    @Autowired
    private IWorkRentService workUseService;
    //用户租赁作品
    @PostMapping("/{workId}")
    @Operation(summary = "用户租赁作品")
    //根据作品id租赁,传入作品id
    public Result<WorkRent> rent(@PathVariable Long workId){
        WorkRent workRent = WorkRent.builder()
                .workId(workId)
                .userId(BaseContext.getCurrentId())
                .build();
        workUseService.save(workRent);
        return Result.success(workRent);
    }
    //解除租赁
    @DeleteMapping("/{workId}/{userId}")
    @Operation(summary = "解除用户租赁")
    public Result unRent(@PathVariable Long workId,@PathVariable Long userId){
        //查找租赁表，删除作品id与用户id匹配的数据
        QueryWrapper<WorkRent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("work_id",workId).eq("user_id",userId);
        workUseService.remove(queryWrapper);
        return Result.success();
    }
    //查询用户是否租赁作品
    @GetMapping("/isRent/{workId}/{userId}")
    @Operation(summary = "查询用户是否租赁作品")
    public Result isRent(@PathVariable Long workId,@PathVariable Long userId){
        QueryWrapper<WorkRent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("work_id",workId).eq("user_id",userId);
        WorkRent workRent = workUseService.getOne(queryWrapper);
        if (workRent!=null){
            return Result.success(true);
        }
        return Result.success(false);
    }
}
